package com.avic.rong.userOrder.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.userOrder.event.CourseJumpEvent;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.userOrder.MineFragmentEvent;
import com.avic.rong.userOrder.adapter.MineOrderViewPagerAdapter;
import com.avic.rong.userOrder.adapter.OrderTypeSelectAdapter;
import com.avic.rong.userOrder.api.OrderStatusApi;
import com.avic.rong.userOrder.bean.OrderStatBean;
import com.avic.rong.userOrder.fragment.MineOrderFragment;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.ToastTools;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.widget.MsgView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

public class MineOrderActivity extends BaseActivity {


    @BindView(R.id.tab_layout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.iv_seach)
    ImageView ivSeach;
    @BindView(R.id.iv_order_select)
    ImageView ivOrderSelect;
    @BindView(R.id.ll_ordertype_select)
    LinearLayout llOrdertypeSelect;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    @BindView(R.id.ll_title_bar)
    LinearLayout llTitleBar;
    private ArrayList<String> titleList = new ArrayList<>();
    private ArrayList<Fragment> fragmentList = new ArrayList<>();
    private final String[] mTitles = {"全部", "待付款", "待发货", "待收货", "交易完成"};
    private int order_state;
    private PopupWindow popupWindow;
    private ArrayList<String> typeList=new ArrayList<>();
    private boolean rotateStart=false;
    private String orderType="全部";
    public static String ORDER_JUMP="orderJump";
    private String  orderMinehome;

    public static TextView tv_title;
    private String  enterType;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_mine_order;
    }

    @Override
    protected void initView() {
        tv_title = findViewById(R.id.tv_title);
        if (getIntent().getIntExtra("order_state", -1) != -1) {
            order_state = getIntent().getIntExtra("order_state", -1);

        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("enterType"))&&!TextUtils.isEmpty(getIntent().getStringExtra("orderType"))){
            orderType = getIntent().getStringExtra("orderType");
            enterType = getIntent().getStringExtra("enterType");
            tv_title.setText(orderType);
        }else {
            tvTitle.setText("我的订单");
        }


        orderMinehome = getIntent().getStringExtra(ORDER_JUMP);


        EventBus.getDefault().register(this);


        orderStart();



        titleList.add("全部");
        titleList.add("待付款");
        titleList.add("待发货");
        titleList.add("待收货");
        titleList.add("交易完成");

        for (int i = 0; i < titleList.size(); i++) {
            MineOrderFragment mineOrderFragment = new MineOrderFragment();
            Bundle bundle = new Bundle();
            if (i == 0) {
                bundle.putString("ORDER_TYPE", "全部");
            } else if (i == 1) {
                bundle.putString("ORDER_TYPE", "待付款");
            } else if (i == 2) {
                bundle.putString("ORDER_TYPE", "待发货");
            } else if (i == 3) {
                bundle.putString("ORDER_TYPE", "待收货");
            } else if (i == 4) {
                bundle.putString("ORDER_TYPE", "交易完成");
            }
            mineOrderFragment.setArguments(bundle);
            fragmentList.add(mineOrderFragment);
        }

        MineOrderViewPagerAdapter mineOrderViewPagerAdapter = new MineOrderViewPagerAdapter(getSupportFragmentManager(), titleList, fragmentList);
        viewPager.setAdapter(mineOrderViewPagerAdapter);
        viewPager.setOffscreenPageLimit(4);
        tabLayout.setViewPager(viewPager, mTitles);
        // 待付款  1   待发货   2    待收货    3     交易成功     4
        if (order_state != -1) {
            if (order_state == 1) {
                viewPager.setCurrentItem(1);
            } else if (order_state == 2) {
                viewPager.setCurrentItem(2);
            } else if (order_state == 3) {
                viewPager.setCurrentItem(3);
            } else if (order_state == 4) {
                viewPager.setCurrentItem(4);
            }
        }
//        /**
//         * 显示未读消息
//         *
//         * @param position 显示tab位置
//         * @param num      num小于等于0显示红点,num大于0显示数字
//         */
//        tabLayout.showMsg(3, 5);
//        /** 设置未读消息偏移,原点为文字的右上角.当控件高度固定,消息提示位置易控制,显示效果佳 */
//        tabLayout.setMsgMargin(3, 0, 10);

//        MsgView rtv_2_3 = tabLayout.getMsgView(3);
//        if (rtv_2_3 != null) {
//            rtv_2_3.setBackgroundColor(getResources().getColor(R.color.color_99C729));
////            rtv_2_3.setTextColor(getResources().getColor(R.color.color_99C729));
//        }
        typeList.add("全部");
        typeList.add("软件服务");
        typeList.add("标准");
        typeList.add("元器件");
        typeList.add("培训");
        typeList.add("会员服务");


    }

    public void orderStart() {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("token", getSharedPreferencesUtil().getLogintoken());
            //订单类型 全部：0，软件：1，元器件 2，标准：4，培训：5，会员服务：8
            if(!TextUtils.isEmpty(enterType)&&enterType.equals("课程")){
                map.put("orderType","5" );
            }else {
                if (orderType.equals("全部")){
                    map.put("orderType","0" );
                }else if (orderType.equals("软件服务")){
                    map.put("orderType","1" );
                }else if (orderType.equals("标准")){
                    map.put("orderType","4" );
                }else if (orderType.equals("元器件")){
                    map.put("orderType","2" );
                }else if (orderType.equals("培训")){
                    map.put("orderType","5" );
                }else if (orderType.equals("会员服务")){
                    map.put("orderType","8" );
                }
            }


            final OrderStatusApi orderStatusApi = new OrderStatusApi(this, simpleOnNextListener);
            orderStatusApi.setCache(false);
            orderStatusApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(orderStatusApi);
        }
    }

    @Override
    protected void addListener() {
        ivSeach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MineOrderActivity.this, OrderSearchActivity.class);
                startActivity(intent);
            }
        });
        llOrdertypeSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rotateStart=!rotateStart;
                ivOrderSelect.setPivotX(ivOrderSelect.getWidth()/2);
                ivOrderSelect.setPivotY(ivOrderSelect.getHeight()/2);//支点在图片中心
                if (rotateStart){
                    ivOrderSelect.setRotation(180);
                    orderTypeSelect();
                }else {
                    ivOrderSelect.setRotation(360);
                    popupWindow.dismiss();
                }

            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(orderMinehome)&&orderMinehome.equals("mine_home")){
                    finish();
                }else {
                    //点击“订单列表返回”切换到我的fragment
                    EventBus.getDefault().postSticky(new MineFragmentEvent());

                    Intent intent = new Intent(MineOrderActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }




            }
        });
    }
    @Subscribe
    public void onEventShowThread(InformUpdate event) {
        if (event != null) {
            if (event.getEventType() == InformUpdate.ORDER_TYPE_INFORM){
                orderType = event.getOrderType();
                popupWindow.dismiss();
                orderStart();


                ivOrderSelect.setPivotX(ivOrderSelect.getWidth()/2);
                ivOrderSelect.setPivotY(ivOrderSelect.getHeight()/2);//支点在图片中心
                ivOrderSelect.setRotation(360);
            }

        }
    }

    private void orderTypeSelect() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.order_type_select_layout, null);
        RecyclerView recyOrdertypeSelect = inflate.findViewById(R.id.recy_ordertype_select);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyOrdertypeSelect.setLayoutManager(linearLayoutManager);
        OrderTypeSelectAdapter orderTypeSelectAdapter = new OrderTypeSelectAdapter(context, typeList,orderType);
        recyOrdertypeSelect.setAdapter(orderTypeSelectAdapter);
        commonPop(inflate);
    }

    //权威评测
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(MineOrderActivity.this, subjects.getMsg());
                return;
            }




            if ((OrderStatBean) subjects.getData() != null) {
                OrderStatBean orderStatBean = (OrderStatBean) subjects.getData();
               /* if (orderStatBean.getAll() != 0) {
                    tabLayout.showMsg(0, orderStatBean.getAll());
                    tabLayout.setMsgMargin(0, 0, 10);
                    MsgView rtv_2_3 = tabLayout.getMsgView(0);
                    if (rtv_2_3 != null) {
                        rtv_2_3.setBackgroundColor(getResources().getColor(R.color.color_99C729));
//            rtv_2_3.setTextColor(getResources().getColor(R.color.color_99C729));
                    }
                }*/
                if (orderStatBean.getWaitPay() >= 0) {
                    tabLayout.showMsg(1, orderStatBean.getWaitPay());
                    tabLayout.setMsgMargin(1, 0, 10);
                    MsgView rtv_2_3 = tabLayout.getMsgView(1);
                    if (rtv_2_3 != null&&orderStatBean.getWaitPay() > 0) {
                        rtv_2_3.setBackgroundColor(getResources().getColor(R.color.white));
                        rtv_2_3.setStrokeColor(getResources().getColor(R.color.color_98c727));
                        rtv_2_3.setStrokeWidth(1);
                        rtv_2_3.setTextColor(getResources().getColor(R.color.color_98c727));
//            rtv_2_3.setTextColor(getResources().getColor(R.color.color_99C729));
                    }else if (rtv_2_3 != null&&orderStatBean.getWaitPay() == 0){
                        rtv_2_3.setBackgroundColor(getResources().getColor(R.color.white));
                        rtv_2_3.setTextColor(getResources().getColor(R.color.color_98c727));
                    }
                }
                if (orderStatBean.getWaitSend() >= 0) {
                    tabLayout.showMsg(2, orderStatBean.getWaitSend());
                    tabLayout.setMsgMargin(2, 0, 10);
                    MsgView rtv_2_3 = tabLayout.getMsgView(2);
                    if (rtv_2_3 != null&&orderStatBean.getWaitSend() > 0) {
                        rtv_2_3.setBackgroundColor(getResources().getColor(R.color.white));
                        rtv_2_3.setStrokeColor(getResources().getColor(R.color.color_98c727));
                        rtv_2_3.setStrokeWidth(1);
                        rtv_2_3.setTextColor(getResources().getColor(R.color.color_98c727));
//            rtv_2_3.setTextColor(getResources().getColor(R.color.color_99C729));
                    }else if (rtv_2_3 != null&&orderStatBean.getWaitSend() == 0){
                        rtv_2_3.setBackgroundColor(getResources().getColor(R.color.white));
                        rtv_2_3.setTextColor(getResources().getColor(R.color.color_98c727));
                    }
                }
                if (orderStatBean.getWaitGet() >= 0) {
                    tabLayout.showMsg(3, orderStatBean.getWaitGet());
                    tabLayout.setMsgMargin(3, 0, 10);
                    MsgView rtv_2_3 = tabLayout.getMsgView(3);
                    if (rtv_2_3 != null&&orderStatBean.getWaitGet() > 0) {
                        rtv_2_3.setBackgroundColor(getResources().getColor(R.color.white));
                        rtv_2_3.setStrokeColor(getResources().getColor(R.color.color_98c727));
                        rtv_2_3.setStrokeWidth(1);
                        rtv_2_3.setTextColor(getResources().getColor(R.color.color_98c727));
//            rtv_2_3.setTextColor(getResources().getColor(R.color.color_99C729));
                    }else if (rtv_2_3 != null&&orderStatBean.getWaitGet() == 0){
                        rtv_2_3.setBackgroundColor(getResources().getColor(R.color.white));
                        rtv_2_3.setTextColor(getResources().getColor(R.color.color_98c727));
                    }
                }
              /*  if (orderStatBean.getFinish() != 0) {
                    tabLayout.showMsg(4, orderStatBean.getFinish());
                    tabLayout.setMsgMargin(4, 0, 10);
                    MsgView rtv_2_3 = tabLayout.getMsgView(4);
                    if (rtv_2_3 != null) {
                        rtv_2_3.setBackgroundColor(getResources().getColor(R.color.color_99C729));
//            rtv_2_3.setTextColor(getResources().getColor(R.color.color_99C729));
                    }
                }*/

                //我的首页课程跳转，需要指定培训刷新
                if (!TextUtils.isEmpty(enterType)&&enterType.equals("课程")){
                    CourseJumpEvent courseJumpEvent = new CourseJumpEvent();
                    courseJumpEvent.setOrderType("培训");
                    EventBus.getDefault().postSticky(courseJumpEvent);
                }
                //当页面请求完数据，将我的课程类型跳转置空
                if(!TextUtils.isEmpty(enterType)&&enterType.equals("课程")){
                    enterType=null;
                }


            }


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        for (int i = 0; i < titleList.size(); i++) {
            fragmentList.get(i).onActivityResult(requestCode, resultCode, data);
        }
    }

    private void commonPop(View view) {
        View view_bg = view.findViewById(R.id.view_bg);
        popupWindow = new PopupWindow(view, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, false);
//        // 产生背景变暗效果
//        WindowManager.LayoutParams lp = getWindow()
//                .getAttributes();
//        lp.alpha = 0.4f;
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
//        getWindow().setAttributes(lp);

//        WindowManager.LayoutParams params = context.getWindow().getAttributes();
//        context.getWindow().setAttributes(params);

        view_bg.setAlpha(0.4f);
//        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(false);
        popupWindow.setTouchable(true);
        //从下往上弹出动画效果
//        popupWindow.setAnimationStyle(R.style.topPopupAnimation);
        popupWindow.showAsDropDown(findViewById(R.id.ll_title_bar), Gravity.BOTTOM, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
//                WindowManager.LayoutParams lp = getWindow()
//                        .getAttributes();
//                lp.alpha = 1f;
//                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
//                getWindow().setAttributes(lp);
            }
        });
    }

    @Subscribe

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
